#!/bin/bash

set -o errexit

test_dir="$(dirname $0)"
. $(dirname $0)/functions
src_dir="$(realpath ${test_dir}/..)"

set_debug

IMAGE=$(echo "$IMAGE" | sed -e 's#percona/#perconalab/#')

if [[ ${DOCKER_NOCACHE:-0} == 1 ]]; then
	no_cache="--no-cache"
fi
if [[ ${DOCKER_SQUASH:-1} == 1 ]]; then
	squash="--squash"
fi

if [[ ${DOCKER_PUSH:-1} == 1 ]]; then
	imgresult="--push=true"
else
	imgresult="--load"
fi

build_operator() {
	if [ "${RELEASE:-1}" = 0 ]; then
		GO_LDFLAGS="-race"
	fi

	export IMAGE
	export DOCKER_DEFAULT_PLATFORM=${DOCKER_DEFAULT_PLATFORM:-"linux/amd64"}
	export GO_LDFLAGS="-w -s -trimpath $GO_LDFLAGS"

	if echo "$DOCKER_DEFAULT_PLATFORM" | grep -q ','; then
		if [ "${DOCKER_PUSH:-1}" = 0 ]; then
			echo "'docker $build_command' doesn't support DOCKER_PUSH=0 option in case of multi-arch builds, please use DOCKER_PUSH=1"
			exit 1
		fi
	fi

	pushd ${src_dir}
	docker buildx build \
		--platform $DOCKER_DEFAULT_PLATFORM \
		--build-arg GIT_COMMIT=$GIT_COMMIT \
		--build-arg GIT_BRANCH=$GIT_BRANCH \
		--build-arg BUILD_TIME=$BUILD_TIME \
		--build-arg GO_LDFLAGS="$GO_LDFLAGS" \
		--progress plain \
		$squash \
		$imgresult \
		$no_cache \
		-t "${IMAGE}" -f build/Dockerfile .
	popd
}

until docker ps; do sleep 1; done
build_operator
